#!/usr/bin/env node

import { readFileSync } from 'fs';

/**
 * Configuration Validation Script
 * Validates that memory configuration is properly loaded
 */

console.log('🔍 MCP Java Decompiler - 配置验证');
console.log('=====================================');

try {
    // Read configuration file
    const configData = readFileSync('./config/server.json', 'utf-8');
    const config = JSON.parse(configData);
    
    console.log('✅ 配置文件加载成功: config/server.json');
    console.log('');
    
    // Validate server memory configuration
    const memoryConfig = config.server?.memory;
    if (memoryConfig) {
        console.log('📋 内存配置:');
        console.log(`   💾 最大内存: ${memoryConfig.maxOldSpaceSize}MB`);
        console.log(`   🗑️  GC启用: ${memoryConfig.enableGC ? '是' : '否'}`);
        console.log(`   ⚡ 自动优化: ${memoryConfig.autoOptimizeForLargeRepository ? '是' : '否'}`);
        
        // Generate recommended NODE_OPTIONS
        var nodeOptions = [`--max-old-space-size=${memoryConfig.maxOldSpaceSize}`];
        if (memoryConfig.enableGC) {
            nodeOptions.push('--expose-gc');
        }
        
        console.log(`   🔧 推荐NODE_OPTIONS: ${nodeOptions.join(' ')}`);
        console.log('');
        
        // Check current environment
        const currentNodeOptions = process.env.NODE_OPTIONS || '';
        console.log('🌍 当前环境:');
        console.log(`   NODE_OPTIONS: ${currentNodeOptions || '(未设置)'}`);
        
        const hasMaxOldSpace = currentNodeOptions.includes('--max-old-space-size');
        const hasExposeGC = currentNodeOptions.includes('--expose-gc');
        
        console.log(`   内存限制设置: ${hasMaxOldSpace ? '✅ 已设置' : '❌ 未设置'}`);
        console.log(`   GC接口暴露: ${hasExposeGC ? '✅ 已设置' : '❌ 未设置'}`);
        console.log('');
    } else {
        console.log('❌ 内存配置缺失');
    }
    
    // Validate other configurations
    console.log('📊 其他配置:');
    console.log(`   主机: ${config.server?.host || 'localhost'}`);
    console.log(`   端口: ${config.server?.port || 3000}`);
    console.log(`   Maven仓库: ${config.maven?.localRepository || '未配置'}`);
    console.log(`   反编译引擎: ${config.decompiler?.defaultEngine || 'cfr'}`);
    console.log(`   CORS: ${config.mcp?.enableCors ? '启用' : '禁用'}`);
    console.log(`   流式传输: ${config.mcp?.enableStreaming ? '启用' : '禁用'}`);
    console.log('');
    
    // Test memory configuration loading in TypeScript
    console.log('🧪 TypeScript配置加载测试:');
    
    const { spawn } = await import('child_process');
    const recommendedOptions = nodeOptions.join(' ');
    
    const testProcess = spawn('node', ['-e', `
        // Import the configuration
        import('./dist/config.js').then(({ config }) => {
            console.log('TypeScript配置加载:', {
                memoryLimit: config.server.memory.maxOldSpaceSize,
                gcEnabled: config.server.memory.enableGC,
                autoOptimize: config.server.memory.autoOptimizeForLargeRepository,
                repository: config.maven.localRepository,
                engine: config.decompiler.defaultEngine
            });
        }).catch(error => {
            console.error('配置加载失败:', error.message);
            process.exit(1);
        });
    `], {
        stdio: ['inherit', 'pipe', 'pipe'],
        env: { ...process.env, NODE_OPTIONS: recommendedOptions }
    });
    
    let output = '';
    let errorOutput = '';
    
    testProcess.stdout.on('data', (data) => {
        output += data.toString();
    });
    
    testProcess.stderr.on('data', (data) => {
        errorOutput += data.toString();
    });
    
    testProcess.on('close', (code) => {
        if (code === 0 && output.trim()) {
            console.log('   ✅ TypeScript配置加载成功');
            try {
                const tsConfig = JSON.parse(output.replace('TypeScript配置加载: ', ''));
                console.log(`   💾 TS内存限制: ${tsConfig.memoryLimit}MB`);
                console.log(`   🗑️  TS GC启用: ${tsConfig.gcEnabled ? '是' : '否'}`);
                console.log(`   ⚡ TS自动优化: ${tsConfig.autoOptimize ? '是' : '否'}`);
            } catch (e) {
                console.log(`   📄 原始输出: ${output.trim()}`);
            }
        } else {
            console.log('   ❌ TypeScript配置加载失败');
            if (errorOutput) {
                console.log(`   错误: ${errorOutput.trim()}`);
            }
        }
        
        console.log('');
        console.log('🏆 配置验证完成!');
        console.log('');
        console.log('💡 使用建议:');
        console.log('   • 使用 npm start 启动本地MCP服务器');
        console.log('   • 使用 npm run start:http 启动HTTP MCP服务器');
        console.log('   • 内存配置将自动从config/server.json应用');
        console.log('   • 如需修改内存限制，编辑config/server.json中的server.memory.maxOldSpaceSize');
    });
    
} catch (error) {
    console.error('❌ 配置验证失败:', error.message);
    process.exit(1);
}